// app/projects/[projectId]/members/page.tsx
'use client';

import { use, useState, useEffect, useRef } from 'react';
import {
  Users,
  UserPlus,
  Crown,
  Shield,
  Eye,
  Edit2,
  Trash2,
  Mail,
  MoreVertical,
  Search,
  Filter,
  Check,
  ChevronsUpDown,
  Loader2,
  UserCog,
  Send
} from 'lucide-react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Badge } from '@/components/ui/badge';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from '@/components/ui/popover';
import {
  Command,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
} from '@/components/ui/command';
import { Label } from '@/components/ui/label';
import { useToast } from '@/hooks/use-toast';
import { cn } from '@/lib/utils';
import {
  Table, TableBody, TableCaption, TableCell, TableHead, TableHeader, TableRow
} from '@/components/ui/table';
import { Separator } from '@/components/ui/separator';
import { getUsersForFilter } from '@/lib/gtc-contract/service';
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { Checkbox } from '@/components/ui/checkbox';
import { sendDataRoomInvitation, sendBulkDataRoomInvitations } from '@/components/project/dataroom-members';

interface Member {
  id: string;
  userId: number;
  user: {
    name: string;
    email: string;
    imageUrl?: string;
    domain: string;
  };
  role: 'owner' | 'admin' | 'editor' | 'viewer';
  addedAt: string;
  lastAccess?: string;
}

interface User {
  id: number;
  name: string;
  email: string;
  domain?: string; // 'partners' | 'internal' 등
}

export default function ProjectMembersPage({
  params: promiseParams
}: {
  params: Promise<{ projectId: string }>
}) {
  // Next.js 15+ params Promise 처리
  const params = use(promiseParams);
  const projectId = params.projectId;

  const [members, setMembers] = useState<Member[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [roleFilter, setRoleFilter] = useState<string>('all');
  const [addMemberOpen, setAddMemberOpen] = useState(false);
  const [editingMember, setEditingMember] = useState<Member | null>(null);
  
  // 프로젝트 정보 상태 추가
  const [projectName, setProjectName] = useState<string>('Data Room');

  // 이메일 전송 관련 상태
  const [sendEmailOnAdd, setSendEmailOnAdd] = useState(true);
  const [selectedMembers, setSelectedMembers] = useState<Set<string>>(new Set());
  const [sendingEmail, setSendingEmail] = useState(false);

  // 사용자 선택 관련 상태
  const [availableUsers, setAvailableUsers] = useState<User[]>([]);
  const [selectedUser, setSelectedUser] = useState<User | null>(null);
  const [userSearchTerm, setUserSearchTerm] = useState('');
  const [userPopoverOpen, setUserPopoverOpen] = useState(false);
  const [loadingUsers, setLoadingUsers] = useState(false);
  const [isExternalUser, setIsExternalUser] = useState(false); // 외부 사용자 여부

  const [newMemberRole, setNewMemberRole] = useState<string>('viewer');
  const [currentUserRole, setCurrentUserRole] = useState<string>('viewer');
  const [page, setPage] = useState(1);
  const pageSize = 20;

  // Command component key management
  const userOptionIdsRef = useRef<Record<number, string>>({});
  const popoverContentId = `popover-content-${Date.now()}`;
  const commandId = `command-${Date.now()}`;

  const { toast } = useToast();

  useEffect(() => {
    setPage(1);
  }, [searchQuery, roleFilter]);

  useEffect(() => {
    fetchMembers();
    checkUserRole();
    fetchProjectInfo();
  }, [projectId]);

  // 프로젝트 정보 가져오기
  const fetchProjectInfo = async () => {
    try {
      const response = await fetch(`/api/projects/${projectId}`);
      const data = await response.json();
      if (data.name) {
        setProjectName(data.name);
      }
    } catch (error) {
      console.error('프로젝트 정보 로드 실패:', error);
    }
  };

  // 다이얼로그가 열릴 때 사용자 목록 가져오기
  useEffect(() => {
    if (addMemberOpen) {
      fetchAvailableUsers();
    } else {
      // 다이얼로그가 닫힐 때 초기화
      setSelectedUser(null);
      setUserSearchTerm('');
      setNewMemberRole('viewer');
      setIsExternalUser(false);
      setSendEmailOnAdd(true);
    }
  }, [addMemberOpen]);

  const fetchAvailableUsers = async () => {
    try {
      setLoadingUsers(true);
      const users = await getUsersForFilter();
      // 이미 프로젝트에 있는 멤버는 제외
      const memberUserIds = members.map(m => m.userId);
      const filteredUsers = users.filter(u => !memberUserIds.includes(u.id));
      setAvailableUsers(filteredUsers);
    } catch (error) {
      console.error('사용자 목록 로드 실패:', error);
      toast({
        title: '오류',
        description: '사용자 목록을 불러올 수 없습니다.',
        variant: 'destructive',
      });
    } finally {
      setLoadingUsers(false);
    }
  };

  const fetchMembers = async () => {
    try {
      setLoading(true);
      const response = await fetch(`/api/projects/${projectId}/members`);
      const data = await response.json();
      setMembers(data.member);
    } catch (error) {
      toast({
        title: '오류',
        description: '멤버 목록을 불러올 수 없습니다.',
        variant: 'destructive',
      });
    } finally {
      setLoading(false);
    }
  };

  const checkUserRole = async () => {
    try {
      const response = await fetch(`/api/projects/${projectId}/access`);
      const data = await response.json();
      setCurrentUserRole(data.role);
    } catch (error) {
      console.error('권한 확인 실패:', error);
    }
  };

  const addMember = async () => {
    if (!selectedUser) {
      toast({
        title: '오류',
        description: '사용자를 선택해주세요.',
        variant: 'destructive',
      });
      return;
    }

    try {
      const response = await fetch(`/api/projects/${projectId}/members`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          userId: selectedUser.id,
          role: newMemberRole,
        }),
      });

      if (!response.ok) throw new Error('멤버 추가 실패');

      // 이메일 전송 옵션이 켜져 있으면 이메일 발송
      if (sendEmailOnAdd) {
        const emailResult = await sendDataRoomInvitation({
          email: selectedUser.email,
          name: selectedUser.name,
          dataRoomName: projectName,
          role: newMemberRole,
          dataRoomUrl: `${window.location.origin}/projects/${projectId}`
        });

        if (emailResult.success) {
          toast({
            title: '성공',
            description: '멤버가 추가되고 초대 이메일이 발송되었습니다.',
          });
        } else {
          toast({
            title: '부분 성공',
            description: '멤버는 추가되었지만 이메일 발송에 실패했습니다.',
            variant: 'default',
          });
        }
      } else {
        toast({
          title: '성공',
          description: '새 멤버가 추가되었습니다.',
        });
      }

      setAddMemberOpen(false);
      fetchMembers();
    } catch (error) {
      toast({
        title: '오류',
        description: '멤버 추가에 실패했습니다.',
        variant: 'destructive',
      });
    }
  };

  // 선택된 멤버들에게 이메일 보내기
  const sendEmailToSelectedMembers = async () => {
    if (selectedMembers.size === 0) {
      toast({
        title: '오류',
        description: '이메일을 보낼 멤버를 선택해주세요.',
        variant: 'destructive',
      });
      return;
    }

    setSendingEmail(true);
    
    try {
      const membersToEmail = members
        .filter(m => selectedMembers.has(m.id))
        .map(m => ({
          email: m.user.email,
          name: m.user.name,
          dataRoomName: projectName,
          role: m.role,
          dataRoomUrl: `${window.location.origin}/projects/${projectId}`
        }));

      const result = await sendBulkDataRoomInvitations(membersToEmail);
      
      if (result.success) {
        toast({
          title: '성공',
          description: result.message,
        });
        setSelectedMembers(new Set());
      } else {
        toast({
          title: '오류',
          description: result.message,
          variant: 'destructive',
        });
      }
    } catch (error) {
      toast({
        title: '오류',
        description: '이메일 발송에 실패했습니다.',
        variant: 'destructive',
      });
    } finally {
      setSendingEmail(false);
    }
  };

  const updateMemberRole = async (memberId: string, newRole: string) => {
    try {
      const response = await fetch(`/api/projects/${projectId}/members/${memberId}`, {
        method: 'PATCH',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ role: newRole }),
      });

      if (!response.ok) throw new Error('역할 수정 실패');

      toast({
        title: '성공',
        description: '멤버 역할이 수정되었습니다.',
      });
      fetchMembers();
      setEditingMember(null);
    } catch (error) {
      toast({
        title: '오류',
        description: '역할 수정에 실패했습니다.',
        variant: 'destructive',
      });
    }
  };

  const removeMember = async (memberId: string) => {
    if (!confirm('정말로 이 멤버를 제거하시겠습니까?')) return;

    try {
      const response = await fetch(`/api/projects/${projectId}/members/${memberId}`, {
        method: 'DELETE',
      });

      if (!response.ok) throw new Error('멤버 제거 실패');

      toast({
        title: '성공',
        description: '멤버가 제거되었습니다.',
      });
      fetchMembers();
    } catch (error) {
      toast({
        title: '오류',
        description: '멤버 제거에 실패했습니다.',
        variant: 'destructive',
      });
    }
  };

  // 개별 멤버에게 이메일 보내기
  const sendEmailToMember = async (member: Member) => {
    setSendingEmail(true);
    
    try {
      const result = await sendDataRoomInvitation({
        email: member.user.email,
        name: member.user.name,
        dataRoomName: projectName,
        role: member.role,
        dataRoomUrl: `${window.location.origin}/projects/${projectId}`
      });
      
      if (result.success) {
        toast({
          title: '성공',
          description: '초대 이메일이 발송되었습니다.',
        });
      } else {
        toast({
          title: '오류',
          description: '이메일 발송에 실패했습니다.',
          variant: 'destructive',
        });
      }
    } catch (error) {
      toast({
        title: '오류',
        description: '이메일 발송에 실패했습니다.',
        variant: 'destructive',
      });
    } finally {
      setSendingEmail(false);
    }
  };

  const getRoleBadge = (role: string) => {
    const config = {
      owner: { icon: Crown, label: 'Owner', variant: 'default' as const, className: 'bg-purple-100 text-purple-800' },
      admin: { icon: Shield, label: 'Admin', variant: 'secondary' as const, className: 'bg-blue-100 text-blue-800' },
      editor: { icon: Edit2, label: 'Editor', variant: 'outline' as const, className: 'bg-green-100 text-green-800' },
      viewer: { icon: Eye, label: 'Viewer', variant: 'outline' as const, className: '' }
    };
    const { icon: Icon, label, variant, className } = config[role] || config.viewer;
    return (
      <Badge variant={variant} className={cn('flex items-center gap-1', className)}>
        <Icon className="h-3 w-3" />
        {label}
      </Badge>
    );
  };

  const filteredMembers = members
    .filter(m => {
      if (roleFilter !== 'all' && m.role !== roleFilter) return false;
      if (!searchQuery) return true;
      const query = searchQuery.toLowerCase();
      return m.user.name.toLowerCase().includes(query) ||
             m.user.email.toLowerCase().includes(query);
    });

  const displayedMembers = filteredMembers.slice((page - 1) * pageSize, page * pageSize);
  const totalPages = Math.ceil(filteredMembers.length / pageSize);

  const canManageMembers = ['owner', 'admin'].includes(currentUserRole);

  // 사용자 필터링 로직
  const filteredUsers = availableUsers.filter(user => {
    const searchLower = userSearchTerm.toLowerCase();
    return user.name.toLowerCase().includes(searchLower) ||
           user.email.toLowerCase().includes(searchLower);
  });

  // 전체 선택/해제
  const toggleSelectAll = () => {
    if (selectedMembers.size === displayedMembers.length) {
      setSelectedMembers(new Set());
    } else {
      setSelectedMembers(new Set(displayedMembers.map(m => m.id)));
    }
  };

  if (loading) {
    return (
      <div className="flex items-center justify-center h-96">
        <Loader2 className="h-8 w-8 animate-spin" />
      </div>
    );
  }

  return (
    <div className="container mx-auto py-8">
      <Card>
        <CardHeader>
          <div className="flex items-center justify-between">
            <div>
              <CardTitle className="flex items-center gap-2">
                <Users className="h-5 w-5" />
                프로젝트 멤버
              </CardTitle>
              <CardDescription>
                프로젝트에 참여 중인 멤버를 관리합니다 ({filteredMembers.length}명)
              </CardDescription>
            </div>
            <div className="flex gap-2">
              {selectedMembers.size > 0 && (
                <Button
                  variant="outline"
                  size="sm"
                  onClick={sendEmailToSelectedMembers}
                  disabled={sendingEmail}
                >
                  {sendingEmail ? (
                    <Loader2 className="h-4 w-4 mr-2 animate-spin" />
                  ) : (
                    <Send className="h-4 w-4 mr-2" />
                  )}
                  선택한 멤버에게 이메일 ({selectedMembers.size})
                </Button>
              )}
              {canManageMembers && (
                <Button 
                  onClick={() => setAddMemberOpen(true)}
                  size="sm"
                >
                  <UserPlus className="h-4 w-4 mr-2" />
                  멤버 추가
                </Button>
              )}
            </div>
          </div>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {/* 필터 영역 */}
            <div className="flex items-center gap-4">
              <div className="flex-1">
                <div className="relative">
                  <Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" />
                  <Input
                    placeholder="이름 또는 이메일로 검색..."
                    value={searchQuery}
                    onChange={(e) => setSearchQuery(e.target.value)}
                    className="pl-9"
                  />
                </div>
              </div>
              <Select value={roleFilter} onValueChange={setRoleFilter}>
                <SelectTrigger className="w-[150px]">
                  <Filter className="h-4 w-4 mr-2" />
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">모든 역할</SelectItem>
                  <SelectItem value="owner">Owner</SelectItem>
                  <SelectItem value="admin">Admin</SelectItem>
                  <SelectItem value="editor">Editor</SelectItem>
                  <SelectItem value="viewer">Viewer</SelectItem>
                </SelectContent>
              </Select>
            </div>

            <Separator />

            {/* 멤버 테이블 */}
            <div className="rounded-md border">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead className="w-[50px]">
                      <Checkbox
                        checked={selectedMembers.size === displayedMembers.length && displayedMembers.length > 0}
                        onCheckedChange={toggleSelectAll}
                      />
                    </TableHead>
                    <TableHead>멤버</TableHead>
                    <TableHead>역할</TableHead>
                    <TableHead>추가일</TableHead>
                    {/* <TableHead>마지막 접속</TableHead> */}
                    {canManageMembers && <TableHead className="w-[100px]">작업</TableHead>}
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {displayedMembers.map((member) => (
                    <TableRow key={member.id}>
                      <TableCell>
                        <Checkbox
                          checked={selectedMembers.has(member.id)}
                          onCheckedChange={(checked) => {
                            const newSelected = new Set(selectedMembers);
                            if (checked) {
                              newSelected.add(member.id);
                            } else {
                              newSelected.delete(member.id);
                            }
                            setSelectedMembers(newSelected);
                          }}
                        />
                      </TableCell>
                      <TableCell>
                        <div className="flex items-center gap-3">
                          <Avatar className="h-8 w-8">
                            <AvatarImage src={member.user.imageUrl} />
                            <AvatarFallback>
                              {member.user.name.split(' ').map(n => n[0]).join('').toUpperCase()}
                            </AvatarFallback>
                          </Avatar>
                          <div>
                            <div className="font-medium">{member.user.name}</div>
                            <div className="text-sm text-muted-foreground">{member.user.email}</div>
                          </div>
                        </div>
                      </TableCell>
                      <TableCell>{getRoleBadge(member.role)}</TableCell>
                      <TableCell className="text-sm text-muted-foreground">
                        {new Date(member.addedAt).toLocaleDateString()}
                      </TableCell>
                      {/* <TableCell className="text-sm text-muted-foreground">
                        {member.lastAccess 
                          ? new Date(member.lastAccess).toLocaleDateString()
                          : '접속 기록 없음'}
                      </TableCell> */}
                      {canManageMembers && (
                        <TableCell>
                          <DropdownMenu>
                            <DropdownMenuTrigger asChild>
                              <Button variant="ghost" size="icon">
                                <MoreVertical className="h-4 w-4" />
                              </Button>
                            </DropdownMenuTrigger>
                            <DropdownMenuContent align="end">
                              <DropdownMenuItem 
                                onClick={() => sendEmailToMember(member)}
                                disabled={sendingEmail}
                              >
                                <Mail className="h-4 w-4 mr-2" />
                                이메일 보내기
                              </DropdownMenuItem>
                              {member.role !== 'owner' && (
                                <>
                                  <DropdownMenuItem onClick={() => setEditingMember(member)}>
                                    <UserCog className="h-4 w-4 mr-2" />
                                    역할 변경
                                  </DropdownMenuItem>
                                  <DropdownMenuSeparator />
                                  <DropdownMenuItem
                                    onClick={() => removeMember(member.id)}
                                    className="text-red-600"
                                  >
                                    <Trash2 className="h-4 w-4 mr-2" />
                                    멤버 제거
                                  </DropdownMenuItem>
                                </>
                              )}
                            </DropdownMenuContent>
                          </DropdownMenu>
                        </TableCell>
                      )}
                    </TableRow>
                  ))}
                  {displayedMembers.length === 0 && (
                    <TableRow>
                      <TableCell colSpan={canManageMembers ? 6 : 5} className="text-center py-8">
                        <div className="text-muted-foreground">
                          {searchQuery || roleFilter !== 'all' 
                            ? '검색 결과가 없습니다.' 
                            : '아직 멤버가 없습니다.'}
                        </div>
                      </TableCell>
                    </TableRow>
                  )}
                </TableBody>
              </Table>
            </div>

            {/* 페이지네이션 */}
            {totalPages > 1 && (
              <div className="flex items-center justify-between">
                <p className="text-sm text-muted-foreground">
                  전체 {filteredMembers.length}명 중 {(page - 1) * pageSize + 1}-
                  {Math.min(page * pageSize, filteredMembers.length)}명 표시
                </p>
                <div className="flex items-center gap-2">
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setPage(p => Math.max(1, p - 1))}
                    disabled={page === 1}
                  >
                    이전
                  </Button>
                  <span className="text-sm">
                    {page} / {totalPages}
                  </span>
                  <Button
                    variant="outline"
                    size="sm"
                    onClick={() => setPage(p => Math.min(totalPages, p + 1))}
                    disabled={page === totalPages}
                  >
                    다음
                  </Button>
                </div>
              </div>
            )}
          </div>
        </CardContent>
      </Card>

      {/* 역할 변경 다이얼로그 */}
      <Dialog open={!!editingMember} onOpenChange={(open) => !open && setEditingMember(null)}>
        <DialogContent>
          <DialogHeader>
            <DialogTitle>역할 변경</DialogTitle>
            <DialogDescription>
              {editingMember?.user.name}님의 역할을 변경합니다.
            </DialogDescription>
          </DialogHeader>
          <div className="space-y-4">
            <Select
              value={editingMember?.role}
              onValueChange={(value) => editingMember && updateMemberRole(editingMember.id, value)}
            >
              <SelectTrigger>
                <SelectValue />
              </SelectTrigger>
              <SelectContent>
                <SelectItem value="viewer">Viewer - 읽기 전용</SelectItem>
                <SelectItem value="editor">Editor - 파일 편집 가능</SelectItem>
                <SelectItem value="admin">Admin - 프로젝트 관리</SelectItem>
              </SelectContent>
            </Select>
          </div>
        </DialogContent>
      </Dialog>

      {/* 멤버 추가 다이얼로그 */}
      <Dialog open={addMemberOpen} onOpenChange={setAddMemberOpen}>
        <DialogContent className="sm:max-w-[500px]">
          <DialogHeader>
            <DialogTitle>새 멤버 추가</DialogTitle>
            <DialogDescription>
              프로젝트에 새 멤버를 추가합니다. 사용자 유형에 따라 부여 가능한 권한이 다릅니다.
            </DialogDescription>
          </DialogHeader>

          <Tabs defaultValue="internal" className="w-full">
            <TabsList className="grid w-full grid-cols-2">
              <TabsTrigger value="internal">내부 사용자</TabsTrigger>
              <TabsTrigger value="external">외부 사용자 (파트너)</TabsTrigger>
            </TabsList>

            <TabsContent value="internal" className="space-y-4 mt-4">
              <div className="space-y-2">
                <Label htmlFor="internal-user">사용자 선택</Label>
                
                {loadingUsers ? (
                  <div className="flex items-center justify-center py-4">
                    <Loader2 className="h-4 w-4 animate-spin" />
                    <span className="ml-2 text-sm text-muted-foreground">사용자 목록 불러오는 중...</span>
                  </div>
                ) : (
                  <>
                    <Popover open={userPopoverOpen} onOpenChange={setUserPopoverOpen}>
                      <PopoverTrigger asChild>
                        <Button
                          variant="outline"
                          role="combobox"
                          aria-expanded={userPopoverOpen}
                          className="w-full justify-between"
                        >
                          <span className="truncate">
                            {selectedUser && !isExternalUser ? (
                              <div className="flex items-center gap-2">
                                <div className="font-medium">{selectedUser.name}</div>
                                <div className="text-xs text-muted-foreground">{selectedUser.email}</div>
                              </div>
                            ) : (
                              "내부 사용자를 선택하세요..."
                            )}
                          </span>
                          <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                        </Button>
                      </PopoverTrigger>
                      <PopoverContent className="w-[460px] p-0">
                        <Command>
                          <CommandInput
                            placeholder="이름 또는 이메일로 검색..."
                            value={userSearchTerm}
                            onValueChange={setUserSearchTerm}
                          />
                          <CommandList
                            className="max-h-[300px]"
                            onWheel={(e) => {
                              e.stopPropagation();
                              const target = e.currentTarget;
                              target.scrollTop += e.deltaY;
                            }}
                          >
                            <CommandEmpty>사용자를 찾을 수 없습니다.</CommandEmpty>
                            <CommandGroup heading="내부 사용자 목록">
                              {filteredUsers
                                .filter(u => u.domain !== 'partners')
                                .map((user) => (
                                  <CommandItem
                                    key={user.id}
                                    onSelect={() => {
                                      setSelectedUser(user);
                                      setUserPopoverOpen(false);
                                      setIsExternalUser(false);
                                      setNewMemberRole('viewer');
                                    }}
                                    value={`${user.name} ${user.email}`}
                                    className="truncate"
                                  >
                                    <Users className="mr-2 h-4 w-4 text-blue-500 flex-shrink-0" />
                                    <div className="flex-1 truncate">
                                      <div className="font-medium truncate">{user.name}</div>
                                      <div className="text-xs text-muted-foreground truncate">{user.email}</div>
                                    </div>
                                    <Check
                                      className={cn(
                                        "ml-2 h-4 w-4 flex-shrink-0",
                                        selectedUser?.id === user.id && !isExternalUser ? "opacity-100" : "opacity-0"
                                      )}
                                    />
                                  </CommandItem>
                                ))}
                            </CommandGroup>
                          </CommandList>
                        </Command>
                      </PopoverContent>
                    </Popover>

                    <p className="text-xs text-muted-foreground">
                      내부 사용자는 모든 역할을 부여할 수 있습니다.
                    </p>
                  </>
                )}
              </div>

              <div className="space-y-2">
                <Label htmlFor="internal-role">역할</Label>
                <Select
                  value={newMemberRole}
                  onValueChange={setNewMemberRole}
                  disabled={!selectedUser || isExternalUser}
                >
                  <SelectTrigger id="internal-role">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="viewer">Viewer - 읽기 전용</SelectItem>
                    <SelectItem value="editor">Editor - 파일 편집 가능</SelectItem>
                    <SelectItem value="admin">Admin - 프로젝트 관리</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </TabsContent>

            <TabsContent value="external" className="space-y-4 mt-4">
              <div className="rounded-lg bg-amber-50 border border-amber-200 p-3 mb-4">
                <p className="text-sm text-amber-800">
                  <strong>보안 정책 안내</strong><br />
                  외부 사용자(파트너)는 보안 정책상 Viewer 권한만 부여 가능합니다.
                </p>
              </div>

              <div className="space-y-2">
                <Label htmlFor="external-user">파트너 선택</Label>

                {loadingUsers ? (
                  <div className="flex items-center justify-center py-4">
                    <Loader2 className="h-4 w-4 animate-spin" />
                    <span className="ml-2 text-sm text-muted-foreground">사용자 목록 불러오는 중...</span>
                  </div>
                ) : (
                  <Popover open={userPopoverOpen} onOpenChange={setUserPopoverOpen}>
                    <PopoverTrigger asChild>
                      <Button
                        variant="outline"
                        role="combobox"
                        aria-expanded={userPopoverOpen}
                        className="w-full justify-between"
                      >
                        <span className="truncate">
                          {selectedUser && selectedUser.domain === 'partners' ? (
                            <span className="flex items-center gap-2">
                              {selectedUser.name}
                              <Badge variant="outline" className="ml-1 text-xs">외부</Badge>
                            </span>
                          ) : (
                            "외부 사용자를 선택하세요..."
                          )}
                        </span>
                        <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
                      </Button>
                    </PopoverTrigger>
                    <PopoverContent className="w-[460px] p-0">
                      <Command>
                        <CommandInput
                          placeholder="이름 또는 이메일로 검색..."
                          value={userSearchTerm}
                          onValueChange={setUserSearchTerm}
                        />
                        <CommandList
                          className="max-h-[300px]"
                          onWheel={(e) => {
                            e.stopPropagation();
                            const target = e.currentTarget;
                            target.scrollTop += e.deltaY;
                          }}
                        >
                          <CommandEmpty>파트너를 찾을 수 없습니다.</CommandEmpty>
                          <CommandGroup heading="파트너 목록">
                            {filteredUsers
                              .filter(u => u.domain === 'partners')
                              .map((user) => (
                                <CommandItem
                                  key={user.id}
                                  onSelect={() => {
                                    setSelectedUser(user);
                                    setUserPopoverOpen(false);
                                    setIsExternalUser(true);
                                    setNewMemberRole('viewer');
                                  }}
                                    value={`${user.name} ${user.email}`}
                                  className="truncate"
                                >
                                  <Users className="mr-2 h-4 w-4 text-amber-600 flex-shrink-0" />
                                  <div className="flex-1 truncate">
                                    <div className="font-medium truncate">{user.name}</div>
                                    <div className="text-xs text-muted-foreground truncate">{user.email}</div>
                                  </div>
                                  <Check
                                    className={cn(
                                      "ml-auto h-4 w-4 flex-shrink-0",
                                      selectedUser?.id === user.id && isExternalUser ? "opacity-100" : "opacity-0"
                                    )}
                                  />
                                </CommandItem>
                              ))}
                          </CommandGroup>
                        </CommandList>
                      </Command>
                    </PopoverContent>
                  </Popover>
                )}
              </div>

              <div className="space-y-2">
                <Label htmlFor="external-role">역할</Label>
                <Select value="viewer" disabled>
                  <SelectTrigger id="external-role" className="opacity-60">
                    <SelectValue />
                  </SelectTrigger>
                  <SelectContent>
                    <SelectItem value="viewer">Viewer - 읽기 전용 (고정)</SelectItem>
                  </SelectContent>
                </Select>
              </div>
            </TabsContent>
          </Tabs>

          {/* 이메일 전송 옵션 */}
          <div className="flex items-center space-x-2 pt-4 border-t">
            <Checkbox
              id="send-email"
              checked={sendEmailOnAdd}
              onCheckedChange={(checked) => setSendEmailOnAdd(checked as boolean)}
            />
            <label
              htmlFor="send-email"
              className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
            >
              접근 권한 안내 이메일 발송
            </label>
          </div>

          <DialogFooter>
            <Button
              variant="outline"
              onClick={() => {
                setAddMemberOpen(false);
                setSelectedUser(null);
                setUserSearchTerm('');
                setNewMemberRole('viewer');
                setIsExternalUser(false);
                setSendEmailOnAdd(true);
              }}
            >
              취소
            </Button>
            <Button
              onClick={addMember}
              disabled={!selectedUser}
            >
              추가하기
            </Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}